package com.deepplin.mongodbmanager.control;

import java.util.List;
import java.util.Set;

import com.deepplin.mongodbmanager.function.MongoDBFunction;
import com.deepplin.mongodbmanager.model.MongoDBSearch;
import com.deepplin.mongodbmanager.model.MongoDBSession;
import com.deepplin.mongodbmanager.util.MongoDBUtil;

public class MongoDBController {	
	
	private static MongoDBController mongoDBController = null;
	private MongoDBSession mgSession; // DB 접속 세션 정보
	
	private MongoDBFunction mgFunction; // 기능구현 클래스	
	
	private MongoDBController(){
		mgFunction = MongoDBFunction.getInstance();
		mgSession = MongoDBSession.getInstance();
	}
	
	/**
	 * MongoDBController 객체 반환
	 * @return
	 */
	public static MongoDBController getInstance(){
		if( mongoDBController == null){			
			mongoDBController = new MongoDBController();
		}
		return mongoDBController;
	}
	
	/**
	 * 
	 * @param HOST
	 * @param PORT
	 * @return
	 */
	public boolean checkHostPORT( String HOST, String PORT){
		
		if( MongoDBUtil.checkHOST(HOST) == false | 	MongoDBUtil.checkPORT(PORT) == false ){
			return false;
		}
		else{
			return true;
		}
	}
	
	/**
	 * 해당 HOST, PORT의 MongoDB 서버의 DB리스트 가져오기
	 * @param HOST
	 * @param PORT
	 * @return
	 */
	public List<String> getDBList( String HOST, String PORT){
		
		// HOST, PORT 유효성 확인
		if( checkHostPORT(HOST, PORT)){
			mgSession.setServerInfo(HOST, PORT);
			MongoDBSearch mgSearch = new MongoDBSearch();
			
			if( mgFunction.getDBList(mgSession , mgSearch) == true){				
				return mgSearch.getListDB();
			}
			else{
				return null;
			}
		}
		else{
			return null;
		}
	}
	
	/**
	 * Connection List 가져오기
	 * @param dbName (database 이름)
	 * @return
	 */
	public Set<String> getCollectionList(String dbName){		
		MongoDBSearch mgSearch = new MongoDBSearch();	
		mgSearch.setStrDBName(dbName);
		
		// 해당 collection이 존재 하는지 체크함
		if( mgSearch.getListDB().contains( dbName) == true){			
			
			if( mgFunction.getCollectionlist(mgSession , mgSearch) == true){
				return mgSearch.getListCollection();
			}
			else{
				return null;
			}
		}
		else{
			return null;
		}				
	}

	/**
	 * Collection내의 문서개수
	 * @param dbName
	 * @param collectionName
	 * @return
	 */
	public long countDocument( String dbName, String collectionName){
		MongoDBSearch mgSearch = new MongoDBSearch();
		
		if( mgSession.isbCheckSession() == true){
			mgSearch.setStrDBName(dbName);
			mgSearch.setStrCollectionName(collectionName);
			return mgFunction.countDocument(mgSession , mgSearch);
		}
		else{
			return -1;
		}
	}	
	
	/**
	 * 
	 * @return
	 */
	public boolean checkConnection(){
		return mgFunction.checkConnection(mgSession);
	}	

	/**
	 * 접속 끊기
	 * @return
	 */
	public boolean disConnection(){
		if( mgSession.isbCheckSession() == true){
			this.mgFunction.disConnection(mgSession);			
		}
		return mgSession.isbCheckSession();
	}
	
}
